
package com.app.megaprosoft.modyimcarcare;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;

import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.ColumnText;

import com.itextpdf.text.Element;
import com.megaprosoft.modyimcarcare.R;


public class Receipt extends Activity {
	
	private static DecimalFormat df = new DecimalFormat("#,###,##0.00");	
	
	int checkRadio = 0; 
	int chackTypr; 
	   private int mYear;
	    private int mMonth;
	    private int mDay;
	    private TextView docID,docDate,dateGetCar,typeCar,RegisterCar,BrandCar,GenerationCar,
	    ColorCar,SumCar,Discount,amountCar,CarpetCar,InsulatorCar,coupon,vipCard,bth,companyShow;
	    connect con = new connect(); 
		ResultSet rs,rs10;
		String RegisterIDT,timeHH,timeMM,sumT,dateT,vipCodeT,DiscountNameT,PriceBTHT,idGetCarT;
		static String ServiceIDT;
		String ServiceTypeT; 
		String BrandT;
		String GenerationT;
		String ColorT;
		String StartTimeT;  
		String EndTimeT;
		String StatusT;
		String CarGroupT;
		String amountT;
		String CarpetT;
		String InsulatorT;
		String liatCar,priceCar,DiscountCar;
		List<Map<String, String>> data = null;
		ListView Lista;
		SimpleAdapter AD;
		String ID;//,idGetCar;
		String docIDT;
		String[] arr ;
		String[] arr2;
		public String filePath;
		
		RadioButton rady,norady;
		RadioGroup checkRady;
		
		
		String NameInput,company,CompanyID;

		File file;
	 static PdfWriter writer;
		
		
		File root2 = Environment.getExternalStorageDirectory();
		File file2 = new File(root2, "backup.pdf");
		String filePath2 = file2.getAbsolutePath();
		
		String FILE = filePath2;
		
		//private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
	    //private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, Font.RED);
	    //private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
	    //private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.activity_receipt);
		
		NameInput = getIntent().getExtras().getString("name");
		company = getIntent().getExtras().getString("CompanyS");
		
		Bundle bundle = getIntent().getExtras();
		ID = bundle.getString("ID");
		//idGetCar = bundle.getString("idGetCar");
	
		
		checkRady= (RadioGroup)findViewById(R.id.radioGroup1);
		rady = (RadioButton)findViewById (R.id.radio0);
		norady = (RadioButton)findViewById (R.id.radio1);
		
		final Button btn1 =  (Button) findViewById(R.id.button1);
		final Button btn2 = (Button) findViewById(R.id.button2);
		
		
		
		
		btn2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
			 
				//Open Form newActivityActritis
				Intent newActivityActritis = new Intent(Receipt.this,MainActivity.class);
				//newActivityActritis.putExtras(newActivityActritis);
				newActivityActritis.putExtra("name", NameInput);
				newActivityActritis.putExtra("CompanyS", company);
				startActivity(newActivityActritis);
				
	}
		});
		
		
		
		
		//============================================Check Rady=====================
		checkRady.setOnCheckedChangeListener ( new RadioGroup.OnCheckedChangeListener ( )
		 {
		 public void onCheckedChanged ( RadioGroup group, int checkedId )
		 {
		 RadioButton checkedRadio = (RadioButton) Receipt.this.findViewById (checkedId);
		 chackTypr = checkedRadio.getId(); 
		 
		   if(chackTypr == R.id.radio0){
			  checkRadio = 1;
	  
		
		   } 
		   else if (chackTypr == R.id.radio1) {
			   checkRadio = 2;
			   
			  
		        } 

		   }
		 });
		 //========================================================================================
		
		
		
			
		
		docID = (TextView)findViewById(R.id.textView6);
		docDate = (TextView)findViewById(R.id.textView7);
		dateGetCar = (TextView)findViewById(R.id.textView8);
		typeCar = (TextView)findViewById(R.id.textView2);
		RegisterCar  = (TextView)findViewById(R.id.textView9);
		BrandCar = (TextView)findViewById(R.id.textView10);
		GenerationCar = (TextView)findViewById(R.id.textView11);
		ColorCar = (TextView)findViewById(R.id.textView12);
		amountCar = (TextView)findViewById(R.id.textView15);
		Discount = (TextView)findViewById(R.id.textView16);
		SumCar = (TextView)findViewById(R.id.textView17);
		CarpetCar = (TextView)findViewById(R.id.textView13);
		InsulatorCar = (TextView)findViewById(R.id.textView14);
		companyShow = (TextView)findViewById(R.id.company);
		
		companyShow.setText(company);
		
		coupon = (TextView)findViewById(R.id.Discount);
		vipCard = (TextView)findViewById(R.id.VIPCode);
		bth = (TextView)findViewById(R.id.disBTH);
		
		Lista = (ListView) findViewById(R.id.listView1);
		
		data = new ArrayList<Map<String,String>>();
		
		try {
			docIDT = generateBillNo();
			//Toast.makeText(Receipt.this, docIDT, Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		docID.setText(docIDT);
		
		final Calendar c = Calendar.getInstance();
		
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH); 
		
        docDate.setText(mDay+"/"+(1+mMonth)+"/"+mYear);
        dateGetCar.setText(mDay+"/"+(1+mMonth)+"/"+mYear);
        
        
    	String sql = "SELECT DataService.Sum AS Sum, "+
    			"CustomerCar.ServiceID AS ServiceID, "+
    			"CustomerCar.Hour AS Hour, "+
    			"CustomerCar.Minute AS Minute, "+
    			"CustomerCar.RegisterID AS RegisterID, "+
    			"CustomerCar.Brand AS Brand, "+
    			"CustomerCar.Generation AS Generation, "+
    			"CustomerCar.Color AS Color, "+
    			"CustomerCar.ServiceType AS ServiceType, "+
    			"CustomerCar.CarGroup AS CarGroup, "+
    			"CarGroup.CarGroupName AS CarGroupName, "+
    			"CustomerCar.Carpet AS Carpet, "+
    			"CustomerCar.Insulator AS Insulator, "+
    			"DataService.date AS date, "+
    			"DataService.id AS id, "+
    			"DataService.List AS List, "+
    			"DataService.price AS price, "+
    			"DataService.amount AS amount, "+
    			"ServiceDetail_old.idGetCar AS idGetCar, "+
    			"ServiceDetail_old.EndTime AS Endtime, " +
    			"DataService.Discount AS Discount, "+
    			"DataService.DiscountName AS DiscountName, "+
    			"DataService.PriceBTH AS PriceBTH, "+
    			"DataService.VIPcode AS VIPcode "+ 
    			"FROM DataService " +

    			"LEFT JOIN CustomerCar "+
    			"on DataService.ServiceID = CustomerCar.ServiceID "+
    			
				"LEFT JOIN CarGroup "+  
				"on CustomerCar.CarGroup = CarGroup.OID "+
    			
    	        "LEFT JOIN ServiceDetail_old "+
    	        "on DataService.ServiceID = ServiceDetail_old.ServiceID "+

    			"WHERE ServiceDetail_old.DTID = '"+ID+"' ";  
    			
    			rs = con.selectData(sql);
    			
    			try {
    				rs.next();
    				RegisterIDT = rs.getString("RegisterID");
    				timeHH = rs.getString("Hour");
    				timeMM = rs.getString("Minute");
    				dateT = rs.getString("date");
    				sumT = rs.getString("Sum");
    				ServiceIDT = rs.getString("ServiceID");
    				ServiceTypeT = rs.getString("ServiceType");
    				BrandT = rs.getString("Brand");
    				GenerationT = rs.getString("Generation");
    				ColorT = rs.getString("Color");
    				EndTimeT = rs.getString("Endtime");
    				CarGroupT = rs.getString("CarGroupName");
    				liatCar = rs.getString("List");
    				priceCar = rs.getString("price");
    				DiscountCar = rs.getString("Discount");
    				amountT = rs.getString("amount");
    				CarpetT = rs.getString("Carpet");
    				InsulatorT = rs.getString("Insulator");
    				vipCodeT = rs.getString("VIPcode");
    				DiscountNameT = rs.getString("DiscountName");
    				PriceBTHT = rs.getString("PriceBTH");
    				idGetCarT =  rs.getString("idGetCar");
    				
    			} catch (SQLException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    			 
		
    			//StartTimeT = timeHH+":"+timeMM;
		
    			typeCar.setText(CarGroupT);
    			RegisterCar.setText(RegisterIDT);
    			BrandCar.setText(BrandT);
    			GenerationCar.setText(GenerationT);
    			ColorCar.setText(ColorT);
    			 
    			arr = liatCar.split(",");
    			arr2 = priceCar.split(",");
    			
    			
    		
    			
    			for(int i=0; i<arr.length; i++){
    				Map<String, String> datanum = new HashMap<String, String>();
    				datanum.put("A", arr[i]);
    				
    				if(arr2[i].equals("-")){
    					datanum.put("B", df.format(0));	
    				}else{
    					datanum.put("B", df.format(Double.parseDouble(arr2[i])));	
    				}
    				
    				data.add(datanum);
               }
    			
    			String[] from = {"A","B"};
    			int[] views = {R.id.textView1,R.id.textView2}; // vamos criar um modelo para as linhas do Adapter
    			AD = new SimpleAdapter(this, data, R.layout.check_list, from, views);
    			Lista.setAdapter(AD);
    			
    		
    
    			
    		//	int a = Integer.parseInt(sumT)+((Integer.parseInt(sumT)*Integer.parseInt(DiscountCar))/100);
    			
    			CarpetCar.setText(CarpetT);
    			InsulatorCar.setText(InsulatorT);
    			amountCar.setText(amountT);
    			
    			SumCar.setText(sumT);
    			
    			if(DiscountNameT.equals("null") || DiscountNameT.equals("��س����͡")){
    				DiscountNameT = "-";
    			}
    			
    			if(vipCodeT.equals("")){
    				vipCodeT = "-";
    			}
    			
    			if(PriceBTHT.equals("")){
    				PriceBTHT = "-";
    			}
    			
    			
    			if(DiscountCar.equals("")){
    				DiscountCar = "-";
    			}
    			
    			
    	 
	
    			
    			coupon.setText(DiscountNameT);
    			vipCard.setText(vipCodeT);
    			bth.setText(PriceBTHT);
    			Discount.setText(DiscountCar);
		
		
		 
		btn1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				//============================Check Radio================================
				if(checkRadio == 0){
					 Toast.makeText(Receipt.this, "��سҵ�Ǩ�ӹǹ��� ��� ����ҧ", Toast.LENGTH_SHORT).show();
				}else{
					
				
				
				//======================================================== 
				
				
				
				
				String sql4 = "DELETE FROM listService";	
				con.addData(sql4);
		
				for(int i = 0;i<arr.length;i++)	{	
	    			String sql3 = "INSERT INTO listService " + 
	    					"(ServiceID,list,price) " +
	    					"VALUES ("+
	    					"'"+ServiceIDT+"'" + ',' + 
	    					"'"+arr[i]+"'" + ',' + 
	    			        "'"+arr2[i]+"'" + ") "; 
	    			
	    			if(con.addData(sql3)){	 
	    				Toast.makeText(Receipt.this, "Inserted data successfully", Toast.LENGTH_SHORT).show();
	    			}else{
	    				 Toast.makeText(Receipt.this, "Inserted data fail", Toast.LENGTH_SHORT).show();
	    		    
	    			}
	    		}
				
String sqlCompany ="SELECT * FROM Company WHERE CompanyName ='"+company+"' ";  
				
				rs10 = con.selectData(sqlCompany);
				try {
					rs10.next();
					
					CompanyID = rs10.getString("OID");
					
				} catch (SQLException e1) {
					
					e1.printStackTrace();
				}
				
				String sql = "INSERT INTO Receipt " + 
						"(docID,SreviceID,idGetCar,dateDoc,date,carType,registerID,brand,generation,color,list," +
						"price,amount,discount,sum,VIPcode,DiscountName,PriceBTH,CreatedDate,Company) " +
			
						"VALUES ("+
						"'"+docIDT+"'" + ',' + 
						"'"+ServiceIDT+"'" + ',' + 
						"'"+idGetCarT+"'" + ',' + 
						"'"+docDate.getText().toString()+"'" + ',' + 
						"'"+dateGetCar.getText().toString()+"'" + ',' + 
						"'"+typeCar.getText().toString()+"'" + ',' +
						"'"+RegisterCar.getText().toString()+"'" + ',' +
						"'"+BrandCar.getText().toString()+"'" + ',' +
						"'"+GenerationCar.getText().toString()+"'" + ',' +
						"'"+ColorCar.getText().toString()+"'" + ',' +
						"'"+liatCar+"'" + ',' +
						"'"+priceCar+"'" + ',' +
						"'"+amountCar.getText().toString()+"'" + ',' +
						"'"+Discount.getText().toString()+"'" + ',' +
						"'"+SumCar.getText().toString()+"'" + ',' +
						"'"+vipCard.getText().toString()+"'" + ',' +
					    "'"+coupon.getText().toString()+"'" + ',' +
						"'"+bth.getText().toString()+"'" + ',' +
				        "GETDATE()"+','+
				        "'"+CompanyID+"') ";
				   
				 
		
				 
				
				if(con.addData(sql)){	 
				    Toast.makeText(Receipt.this, "Inserted data successfully", Toast.LENGTH_SHORT).show();
					
					   String sql2 = "DELETE FROM ServiceDetail_old WHERE DTID = '"+ID+"' ";  
					   if(con.addData(sql2)){
						   Toast.makeText(Receipt.this, "Delete data successfully", Toast.LENGTH_SHORT).show();
						   pdf();	
					   }else{
						   Toast.makeText(Receipt.this, "Delete data fail" , Toast.LENGTH_SHORT).show();
						  
					   }
		
				
				}else{
					  Toast.makeText(Receipt.this, "Inserted data fail" , Toast.LENGTH_SHORT).show();
					 
	

					  
					  
					      Log.i("docIDT",docIDT);
						  Log.i("ServiceIDT",ServiceIDT);
						  Log.i("idGetCar",ServiceIDT);
					 
						  Log.i("docDate",docDate.getText().toString());
						  Log.i("dateGetCar",dateGetCar.getText().toString());
						  Log.i("typeCar",typeCar.getText().toString());
						  Log.i("RegisterCar",RegisterCar.getText().toString());
						  Log.i("BrandCar",BrandCar.getText().toString());
						  Log.i("GenerationCar",GenerationCar.getText().toString());
						  Log.i("ColorCar",ColorCar.getText().toString());
						  Log.i("liatCar",liatCar);
						  Log.i("priceCar",priceCar);
						  Log.i("amountCar",amountCar.getText().toString());
						  Log.i("Discount",Discount.getText().toString());
						  Log.i("SumCar",SumCar.getText().toString());
						  Log.i("vipCard",vipCard.getText().toString());
						  Log.i("coupon",coupon.getText().toString());
						  Log.i("bth",bth.getText().toString());
		}
					
				

				}	
				
			}//else
			
		});
		
		
		btn2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
			 
				//Open Form newActivityActritis
				Intent newActivityActritis = new Intent(Receipt.this,MainActivity.class);
				//newActivityActritis.putExtras(newActivityActritis);
				newActivityActritis.putExtra("name", NameInput);
				newActivityActritis.putExtra("CompanyS", company);
				startActivity(newActivityActritis);
				
	}
		});

		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.receipt, menu);
		return true;
	}
	
	
	
	public String generateBillNo() throws Exception{

	      
		     String StrSql = "SELECT COUNT(docID)+1," +
		     		  "MONTH(GETDATE()), "+
		    		  "CONVERT(VARCHAR(2), GETDATE(), 11) "+
                      "FROM Receipt "+
                      "WHERE CONVERT(VARCHAR(7),[CreatedDate], 111) = CONVERT(VARCHAR(7), GETDATE(), 111) ";
		
	
		
		rs = con.selectData(StrSql);
		
		String No = "";
			
		if(rs.next()){
			if(rs.getInt(1) < 10)
				No = "00"+rs.getInt(1);
			else if(rs.getInt(1) < 100)
				No = "0"+rs.getInt(1);
			else
				No = ""+rs.getInt(1);
		

			return ""+rs.getInt(3)+""+rs.getInt(2)+No;	// Prefix + YYMMDD + XXXX
			
		}else{
			
			return null;
			//return null;
		}
	}
	 
	
	
	public void print(){
		
	/*	
try {	
	String sql = "SELECT Receipt.docID AS docID "+
		    ",Receipt.SreviceID AS SreviceID " +
		    ",Receipt.idGetCar AS idGetCar "+
		    ",Receipt.dateDoc AS dateDoc "+
		    ",Receipt.date AS date "+
		    ",Receipt.carType AS carType "+
		    ",Receipt.registerID AS registerID "+
		    ",Receipt.brand AS brand "+
		    ",Receipt.generation AS generation "+
		    ",Receipt.color AS color "+
		    ",listService.list AS list "+
		    ",listService.price AS price "+
		    ",Receipt.amount AS amount "+
		    ",Receipt.discount AS discount "+
		    ",Receipt.sum AS sum "+
		    ",Receipt.CreatedDate AS CreatedDate "+
		    "FROM Receipt "+
		 
		    "LEFT JOIN listService  "+
		    "on Receipt.SreviceID = listService.ServiceID "+
		  
	    	"WHERE Receipt.SreviceID = '"+ServiceIDT+"' ";
		ResultSet rs;  
		
		rs = con.selectData(sql);
		
		ArrayList<HashMap<String, String>> data = null;
		data = new ArrayList<HashMap<String,String>>();
		try {
			while(rs.next()) {
		   HashMap<String, String>  datanum = new HashMap<String, String>();
		  datanum.put("a", rs.getString("list"));
		  datanum.put("b", rs.getString("price"));
		  datanum.put("c", rs.getString("SreviceID"));

		  data.add(datanum); 
			      		
			}
		} catch (SQLException e) {
			//TODO Auto-generated catch block
			e.printStackTrace();
		//	System.out.println("NO");
		}
		
		

	System.out.println(""+data.size());
	
		File root = Environment.getExternalStorageDirectory();
		file = new File(root, "backup.txt");
		filePath = file.getAbsolutePath();
		FileWriter fw = new FileWriter(file);
	    BufferedWriter out = new BufferedWriter(fw);
	    out.write("�����");
	    out.newLine();
	    out.write(data.get(0).get("c").toString());
	    
		out.write("��¡��"+"                               "+"�Ҥ�");
		
		
		for (HashMap<String, String> hashMap : data) {
			String writeData = hashMap.get("a")+"                               "+
		                              hashMap.get("b");

	        Log.i("Data", writeData);
			out.newLine(); 
			out.write(writeData);
			} 
		out.close();
	   Toast.makeText(Receipt.this, "��¹", Toast.LENGTH_SHORT).show();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		Toast.makeText(Receipt.this, "�����¹", Toast.LENGTH_SHORT).show();
	}
*/


 
				
		Uri uri = Uri.fromFile(file2);
		Intent intent = new Intent(Intent.ACTION_SEND);
		String mimeType = MimeTypeMap.getSingleton()
		        .getMimeTypeFromExtension(MimeTypeMap
		                .getFileExtensionFromUrl(filePath2));
		//intent.setDataAndType(uri, mimeType);
		//startActivity(Intent.createChooser(intent, "Open file with"));
		intent.setType(mimeType);
		intent.putExtra(Intent.EXTRA_STREAM, uri );
		startActivity(Intent.createChooser(intent, "Share file via"));
	}
	 
	public void pdf(){
		 

	    
		   try {
			      Document document = new Document();
			      Rectangle pagesize = new Rectangle(190f, 720f);
			      document.setPageSize(pagesize);
			      document.setMargins(0, 0, 0, 0);
		
			     writer = PdfWriter.getInstance(document, new FileOutputStream(FILE));
			      document.open();
			    
			      addMetaData(document);
			  
			    //  addTitlePage(document);
			      addContent(document);
			      document.close();
			      
			      
			      Toast.makeText(Receipt.this, "��¹", Toast.LENGTH_SHORT).show(); 

			     print();
			    } catch (Exception e) {
			      e.printStackTrace();
			      Toast.makeText(Receipt.this, "�����¹ __", Toast.LENGTH_SHORT).show();
			    }
		   
	    }
	 
		
		
		
	// iText allows to add metadata to the PDF which can be viewed in your Adobe
	  // Reader
	  // under File -> Properties
	  private static void addMetaData(Document document) {
	    document.addTitle("My first PDF");
	    document.addSubject("Using iText");
	    document.addKeywords("Java, PDF, iText");
	    document.addAuthor("Lars Vogel");
	    document.addCreator("Lars Vogel");
	  }

	
	  private static void addContent(Document document) throws DocumentException, IOException {
		  
		  connect con = new connect();

			File path = new File(Environment.getExternalStorageDirectory(), "cordia.ttf");
			String a = path.getAbsolutePath();
			System.out.println(a);
		  
		
		 BaseFont font = BaseFont.createFont(a, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		 Font title = new Font(font, 10, Font.BOLD);	
		 Font content = new Font(font, 8, Font.NORMAL);	
		 
		 
		 

			String sql = "SELECT Receipt.docID AS docID "+
				    ",Receipt.SreviceID AS SreviceID " +
				    ",Receipt.idGetCar AS idGetCar "+
				    ",Receipt.dateDoc AS dateDoc "+
				    ",Receipt.date AS date "+
				    ",Receipt.carType AS carType "+
				    ",Receipt.registerID AS registerID "+
				    ",Receipt.brand AS brand "+
				    ",Receipt.generation AS generation "+
				    ",Receipt.color AS color "+
				    ",listService.list AS list "+
				    ",listService.price AS price "+
				    ",Receipt.amount AS amount "+
				    ",Receipt.discount AS discount "+
				    ",Receipt.sum AS sum "+
				    ",Receipt.CreatedDate AS CreatedDate "+
				    "FROM Receipt "+
				 
				    "LEFT JOIN listService  "+
				    "on Receipt.SreviceID = listService.ServiceID "+
				    
 					
				  
			    	"WHERE Receipt.SreviceID = '"+ServiceIDT+"' ";
			
							ResultSet rs;  
							
							rs = con.selectData(sql);
							
							ArrayList<HashMap<String, String>> data = null;
							data = new ArrayList<HashMap<String,String>>();
							try {
								while(rs.next()) {
							HashMap<String, String>  datanum = new HashMap<String, String>();
							datanum.put("list", rs.getString("list"));
							datanum.put("price", rs.getString("price"));
							datanum.put("docID", rs.getString("docID"));
							datanum.put("dateDoc", rs.getString("dateDoc"));
							datanum.put("date", rs.getString("date"));
							datanum.put("carType", rs.getString("carType"));
							datanum.put("registerID", rs.getString("registerID"));
							datanum.put("brand", rs.getString("brand"));
							datanum.put("generation", rs.getString("generation"));
							datanum.put("color", rs.getString("color"));
							datanum.put("amount", rs.getString("amount"));		
							datanum.put("discount", rs.getString("discount"));		
							datanum.put("sum", rs.getString("sum"));		
							datanum.put("SreviceID", rs.getString("SreviceID"));		
							data.add(datanum); 
				
								}
							} catch (SQLException e) {
								//TODO Auto-generated catch block
								e.printStackTrace();
							//	System.out.println("NO");
							}


										 
	  
		 Paragraph prefaceh = new Paragraph(); 
         prefaceh.add(new Phrase("�����",title));
         prefaceh.setAlignment(Element.ALIGN_CENTER);
         addEmptyLine(prefaceh, 1);
         document.add(prefaceh);
         
         Paragraph preface = new Paragraph(); 
         preface.add(new Phrase("�ٹ���������ö����ѹ",content));
         preface.setAlignment(Element.ALIGN_CENTER);
         document.add(preface);
         
     //==============================================HEAD TITLE===================================================   
         Paragraph subTitle = new Paragraph(); 
         
         PdfPTable table1 = new PdfPTable(2);
         PdfPTable table = new PdfPTable(2);
         
         float[] setsize1 = new float[]{45,55};   
         table1.setWidths(setsize1);
         
 	     table1.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
 	    table1.getDefaultCell().setBorder(0);
 	     table1.addCell("");
 	    
 	     table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
	     table.getDefaultCell().setBorder(0);
 	    
 	 
 	     table.addCell(new Phrase("�Ţ����͡���",content));
	     table.addCell(new Phrase(":   "+data.get(1).get("docID").toString(),content));
	     table.addCell(new Phrase("�ѹ����͡�͡���",content));
	     table.addCell(new Phrase(":   "+data.get(1).get("dateDoc").toString(),content));
	     table.addCell(new Phrase("�ѹ����Ѻö",content));
	     table.addCell(new Phrase(":   "+data.get(1).get("date").toString(),content));
	 
	     table1.addCell(table);

         subTitle.add(table1);
         subTitle.setAlignment(Element.ALIGN_RIGHT);
         addEmptyLine(subTitle, 1);
         document.add(subTitle); 
         
         
     //==============================================DETAIL===================================================    
         Paragraph carDetail = new Paragraph(); 
         
         PdfPTable datatable1 = new PdfPTable(2);
         PdfPTable subtable = new PdfPTable(2);
         PdfPTable subtable2 = new PdfPTable(2);
          
         float[] datatable1Size = new float[]{53,47};  
         float[] widths = new float[]{40,60};   
         float[] widths2 = new float[]{15,85};   
         datatable1.setWidths(datatable1Size);
         subtable.setWidths(widths);
         subtable2.setWidths(widths2);
         
         
           datatable1.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
       datatable1.getDefaultCell().setBorder(0);
         
    //Sub table Table 1
         subtable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
       subtable.getDefaultCell().setBorder(0);
         
         subtable.addCell(new Phrase("������ö",content));
         subtable.addCell(new Phrase(": "+data.get(1).get("carType").toString(),content));
         subtable.addCell(new Phrase("����¹",content));
         subtable.addCell(new Phrase(": "+data.get(1).get("registerID").toString(),content));
         subtable.addCell(new Phrase("������",content));
         subtable.addCell(new Phrase(": "+data.get(1).get("brand").toString(),content));
       //add table 1
         datatable1.addCell(subtable);
      
       //Sub table Table 1
         subtable2.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        subtable2.getDefaultCell().setBorder(0);
         
         
         subtable2.addCell(new Phrase("���",content));
         subtable2.addCell(new Phrase(": "+data.get(1).get("generation").toString(),content));
         subtable2.addCell(new Phrase("��",content));
         subtable2.addCell(new Phrase(": "+data.get(1).get("color").toString(),content));
         subtable2.addCell(new Phrase(""));
         subtable2.addCell(new Phrase(""));
       //add table 2
         datatable1.addCell(subtable2);
         
         carDetail.add(datatable1);
         addEmptyLine(carDetail, 1);
         document.add(carDetail); 
  
         //==============================================LIST DETAIL===================================================      
         
         
         
         Paragraph list = new Paragraph(); 
         PdfPTable tableList = new PdfPTable(2);
         
         float[] widths3 = new float[]{80,20};   
         tableList.setWidths(widths3);
         
         Log.i("pppppp", ""+tableList.getDefaultCell().getPaddingBottom());
         tableList.getDefaultCell().setPaddingBottom(1);
         tableList.setTotalWidth(10);
       
         
         PdfPCell c1 = new PdfPCell(new Phrase("��¡��",content));
	     c1.setHorizontalAlignment(Element.ALIGN_CENTER);
	     c1.setPaddingBottom(2);
	     tableList.addCell(c1);
          
	     Log.i("Size ",""+data.size());
	     
         c1 = new PdfPCell(new Phrase("�Ҥ�(�ҷ)",content));
	     c1.setHorizontalAlignment(Element.ALIGN_CENTER);
	     c1.setPaddingBottom(2); 
	     tableList.addCell(c1);
      
        for(int i = 0 ; i < data.size() ; i++){
     		
        	
     		
             tableList.addCell(new Phrase("  "+data.get(i).get("list").toString(),content));
             
             
     		 if(data.get(i).get("price").toString().equals("-")){
     			 
     			c1 = new PdfPCell(new Phrase("-",content)); 
     		 }else{
     			c1 = new PdfPCell(new Phrase(df.format(Double.parseDouble(data.get(i).get("price").toString())),content));
     		 }
     		 
     		
    	     c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    	     c1.setPaddingBottom(1);
    	     tableList.addCell(c1);
    	    
	        System.out.println(data.get(i).get("list").toString()+"     "+data.get(i).get("price").toString());	
	        
        }
        
      
      
     	
     	  //==============================================SUMMARY DETAIL===================================================   
     	
         
    	
         c1 = new PdfPCell(new Phrase("���  ",content));
	     c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
	     c1.setPaddingBottom(1);
	     tableList.addCell(c1);
	        	
	     c1 = new PdfPCell(new Phrase(df.format(Double.parseDouble(data.get(0).get("amount").toString())),content));
	     c1.setHorizontalAlignment(Element.ALIGN_CENTER);
	     c1.setPaddingBottom(1);
	     tableList.addCell(c1);
	       
	    
	     c1 = new PdfPCell(new Phrase("��ǹŴ  ",content));
	     c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
	     c1.setPaddingBottom(1);
	     tableList.addCell(c1);
	     
	     c1 = new PdfPCell(new Phrase(data.get(1).get("discount").toString()+"  %",content));
	     c1.setHorizontalAlignment(Element.ALIGN_CENTER);
	     c1.setPaddingBottom(1);
	     tableList.addCell(c1);
	     
	     c1 = new PdfPCell(new Phrase("�ʹ�Թ���������  ",content));
	     c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
	     c1.setPaddingBottom(1);
	     tableList.addCell(c1);
	     
	     c1 = new PdfPCell(new Phrase(df.format(Double.parseDouble(data.get(0).get("sum").toString())),content));
	     c1.setHorizontalAlignment(Element.ALIGN_CENTER);
	     c1.setPaddingBottom(1);
	     tableList.addCell(c1);
	     
     	
	     list.add(tableList);
	     document.add(tableList); 
       
	  }

	  private static void addEmptyLine(Paragraph paragraph, int number) {
	    for (int i = 0; i < number; i++) {
	      paragraph.add(new Paragraph(""));
	    }
	  }

	
	
	 
	  
	  
	  @Override
		public void onBackPressed() {
		  
		        new AlertDialog.Builder(this)
		        .setTitle("¡��ԡ��÷���¡��")
		        .setMessage("��Ѻ�˹����ѡ")
		                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

		                    public void onClick(DialogInterface arg0, int arg1) {
		                        Intent newActivity = new Intent(getApplicationContext(),MainActivity.class);	                          
		                        newActivity.putExtra("name", NameInput);
		                        newActivity.putExtra("CompanyS", company);
		                        startActivity(newActivity);
		                        finish();
		                        overridePendingTransition(R.layout.fadeendout,R.layout.fadeendin);
		                    }
		                })
		                .setPositiveButton(android.R.string.no, null).create().show();
		    

		}
	

}
